#!/usr/bin/bash

source ./color.sh
source ./checkos.sh
source ./init.sh
# 数据库安装目录
install_dir=/usr/local/mysql
# 数据存放目录
data_dir=${install_dir}/data
# 配置文件存放目录
config_dir=/etc
# 解压目录名称
source_dir=mysql-5.7.27
# 默认端口
port=3306
# 源码包名称
packagename="mysql-boost-5.7.27.tar.gz"
# 编译线程数
cpus=`grep "processor" /proc/cpuinfo | wc -l`

checkEnv(){
    [ -d /var/lib/mysql ] && color yellow "检测到本机可能使用yum安装了mysql，可能会造成冲突，请问是否继续安装[Y|N]"
    read result
    if [ "$result" = 'Y' ];then
        color green "安装继续"
    else
        color green "退出脚本"
        exit 1
    fi
    [ -d /usr/local/mysql ] && color red "检测到${install_dir}已存在，请手动处理" && exit 1 || \
    color green "环境检测完成"
}

installPackage(){
    yum -y install ncurses ncurses-devel openssl-devel bison gcc gcc-c++ make glibc automake autoconf cmake && \
    color green "依赖包安装完成" || \
    color red "依赖包安装异常，请修复yum源[需要官方yum以及epelyum]"
    color green "开始准备源码包"
    sed -n -e '1,/^exit 0$/!p' $0 > ./$packagename
    tar xvf $packagename && \
    color green "源码包准备完成" && \
    cd $source_dir/
    cmake . \
    -DWITH_BOOST=boost/boost_1_59_0/ \
    -DCMAKE_INSTALL_PREFIX=$install_dir \
    -DSYSCONFDIR=$config_dir \
    -DMYSQL_DATADIR=$data_dir \
    -DINSTALL_MANDIR=/usr/share/man \
    -DMYSQL_TCP_PORT=$port \
    -DMYSQL_UNIX_ADDR=/tmp/mysql.sock \
    -DDEFAULT_CHARSET=utf8 \
    -DEXTRA_CHARSETS=all \
    -DDEFAULT_COLLATION=utf8_general_ci \
    -DWITH_READLINE=1 \
    -DWITH_SSL=system \
    -DWITH_EMBEDDED_SERVER=1 \
    -DENABLED_LOCAL_INFILE=1 \
    -DWITH_INNOBASE_STORAGE_ENGINE=1 && \
    make -j $cpus && make install && \
    color green "编译安装完成"
}

down(){
    cat >> /etc/profile.d/source_mysql.sh <<\EOF
    PATH=/usr/local/mysql/bin:$PATH
    export PATH
EOF
    password=$(${install_dir}/bin/mysqld --initialize --user=mysql --basedir=$install_dir --datadir=$data_dir 2>&1 | grep "A temporary password" | awk '{print $NF}')
    if [ -n "$password" ];then
        color green "初始化完成，初始密码为$password"
        color green "通过mysqladmin -p$password password '新密码'进行修改密码"
        color green "启动数据库 mysqld_safe &\nmysql 安装完成"
    else
        color red   "初始化异常，请手动检查"
    fi
    read -p '是否需要清理安装环境[Y|N]: ' ask
    if [ "$ask" = 'Y' ];then
        rm -rvf $source_dir
        rm -rvf $packagename
        color green "清理完成"
    else
        color green "脚本退出"
    fi
}


main(){
    checkEnv
    installPackage
    down
}
main
exit 0
